package com.example.testjenkins.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

public class TestFairLock {
    public static void main(String[] args) {


        Ticket ticket = new Ticket();
        Thread t1 = new Thread(() -> {
            while (ticket.isNotOver()) {
                ticket.sale("a");
            }
        });
        new Thread(() -> {
            while (ticket.isNotOver()) {
                ticket.sale("b");
            }
        });

    }

    static class Ticket {
        private int number = 50;
        final ReentrantLock lock = new ReentrantLock();

        public void sale(String name) {
            lock.lock();
            try {
                if (number > 0) {
                    number--;
                    System.out.println(name + "卖了票，还剩票数：" + number);
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public boolean isNotOver() {
            return number > 0;
        }
    }
}
